<script>
import KInput from './components/KInput'
import { SETTING_KEY } from '@/views/visitor/show.vue'
export default {
  components: {
    KInput
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('账号不能为空'))
      } else {
        const reg = /^1[3-9][0-9]\d{8}$/
        // 这里定义的reg变量没有加引号，所以是一种特殊的数据类型，即正则，可以直接用test()方法
        if (reg.test(value)) {
          callback()
        } else {
          // 具体错误信息没有提示
          return callback(new Error('请输入正确的账号'))
        }
      }
    }
    return {
      form: {
        account: '',
        password: ''
      },
      isSubmitting: false,
      redirect: null,
      otherQuery: null,
      formRules: {
        account: [
          { min: 11, message: '账号不足11位', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: ['blur', 'change'] }
        ]
      },
      remember: false
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    if (window.localStorage.getItem('user_account')) {
      this.form = JSON.parse(window.localStorage.getItem('user_account'))
    }
  },
  mounted() {
    this.initialFocus()
  },
  methods: {
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    toPageRegister() {
      this.$router.push('/company/register')
    },
    initialFocus() {
      const { account, password } = this.form
      if (typeof account !== 'string' || account.trim() === '') {
                this.$refs['accountRef']?.focus?.()
                return
      }

      if (typeof password !== 'string' || password.trim() === '') {
                this.$refs['passwordRef']?.focus?.()
                return
      }
    },
    validate() {
            this.$refs['form']?.validate?.()
    },
    handleLogin() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (this.remember) {
          window.localStorage.setItem('user_account', JSON.stringify(this.form))
        } else {
          window.localStorage.removeItem('user_account')
        }
        this.isSubmitting = true
        this.$store.dispatch('user/login', { username: this.form.account, password: this.form.password, remember: this.remember })
          .then(() => {
            window.localStorage.removeItem(SETTING_KEY)
            this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
            this.isSubmitting = false
          })
          .catch((err) => {
            console.log(err?.response?.status)
            const { response: { status, data: { message }}} = err
            if (status === 400 || status === 410 || status === 422) {
              this.$message({
                message: message,
                type: 'error'
              })
            }
            this.isSubmitting = false
          }).finally(() => {
            this.isSubmitting = false
          })
      })
    }
  }
}
</script>

<template>
  <div class="login-container" :style="{ backgroundImage: `url(${require('@/assets/login/bg.svg')})` }">
    <div class="decoration-layout">
      <img
        style="width: 44%;"
        src="https://obs-user-test.obs.cn-east-3.myhuaweicloud.com:443/logo/test_1685699935_9z2SDQ5UcZ.png"
      >
      <img style="width: 100%;" :src="require('@/assets/login/decoration.svg')">
    </div>

    <div class="form-container">
      <el-form ref="form" :model="form" :rules="formRules">
        <el-form-item>
          <div class="title">登录</div>
        </el-form-item>

        <el-form-item prop="account">
          <KInput ref="accountRef" v-model="form.account" placeholder="请输入账号" oninput="value=value.replace(/[^\d]/g,'')">
            <template slot="prefix">
              <svg-icon icon-class="input-user" class="icon" />
            </template>
          </KInput>
        </el-form-item>

        <el-form-item prop="password">
          <KInput
            ref="passwordRef"
            v-model="form.password"
            placeholder="请输入密码"
            type="password"
            @keyup.enter.native="handleLogin"
          >
            <template slot="prefix"><svg-icon icon-class="locker" class="icon" /></template>
          </KInput>
        </el-form-item>

        <el-checkbox v-model="remember">记住我</el-checkbox>

        <el-form-item style="margin-top: 50px;">
          <el-button style="width: 100%;" size="lagre" type="primary" :loading="isSubmitting" @click="handleLogin">登录</el-button>
        </el-form-item>

        <el-form-item style="text-align: center;font-size: 14px;">
          <span style="color: #8E8E8E;">还没有账号？</span>
          <span style="color: #2F88FF;cursor: pointer;" @click="toPageRegister">立即注册</span>
        </el-form-item>
      </el-form>

      <div class="footer">
        <span class="copyright">中模云（宁波）科技有限公司</span>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.login-container {
    width: 100vw;
    height: 100vh;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;

    .decoration-layout {
        width: 34%;
        text-align: center;
        position: absolute;
        top: 8%;
        left: 10%;
    }

    .form-container {
        min-width: 350px;
        width: 23%;
        // height: 54%;
        background-color: white;
        border-radius: 6px;
        position: absolute;
        right: 12%;
        top: 18%;
        padding: 20px 54px;

        .footer {
            position: absolute;
            bottom: 20px;
            left: 0;
            width: 100%;
            text-align: center;

            .copyright {
                position: relative;
                color: #8E8E8E;
                font-size: 14px;

                &::after,
                &::before {
                    position: absolute;
                    content: ' ';
                    display: inline-block;
                    width: 66px;
                    height: 1px;
                    background-color: #DCDFE6;
                    top: calc(50% - 0.5px);
                    z-index: 99;
                }

                &::before {
                    left: calc(-66px + -10px);
                }

                &::after {
                    right: calc(-66px + -10px);
                }
            }
        }

        .title {
            font-size: 24px;
            color: #3D3D3D;
            text-align: center;
            padding: 60px 0 20px 0;
            position: relative;

            &::after {
                content: '';
                display: block;
                height: 4px;
                width: 48px;
                background-color: #2F88FF;
                position: absolute;
                bottom: 10px;
                left: calc(50% - 24px);
            }
        }
    }
}
</style>
